#include "Tree.h"
#include "Parser.h"
//#include <QString>
#include <map>
#include <utility>
#include <vector>
using namespace std;

template <class T>
Tree<T>::Tree(T item)
{
    this->_item = item;
}
template <class T>
void Tree<T>::insert(Tree *branch)
{
    branch->father = this;
    branches.push_back(branch);
}

Tree<string> tree_generator(string listraw)
{
    Tree<string> *root = new Tree<string>("");
    vector<string> lists = listCut(listraw);
    map<int, Tree<string> *> dads;
    dads[-1] = root;
    int cur = -1;
    for (auto i : lists)
    {
        int tabs = Counter(i, ' ');
        Tree<string> *newTree = new Tree<string>(i);
        if (tabs > cur)
        {
            dads[cur]->insert(newTree);
            dads[tabs] = newTree; //candidate dad.
        }
        else if (tabs == cur)
        {
            dads[cur]->father->insert(newTree);
            dads[tabs] = newTree;
        }
        else
        {
            if (dads.count(tabs))
            {
                dads[tabs]->father->insert(newTree);
                dads[tabs] = newTree;
            }
            else
            {
                for (int i = tabs; i >= 0; i--)
                {
                    if (dads.count(i - 1))
                    {
                        if (dads[i - 1]->root())
                        {
                            dads[i - 1]->insert(newTree);
                        }else{
                            dads[i - 1]->father->insert(newTree);
                        }
                        dads[tabs] = newTree;
                        break;
                    }
                }
            }
        }
        cur = tabs;
    }
    return *root;
}
template <class T>
void Tree<T>::printTree(int indent)
{
    cout << string(indent, '\t') << indent << ". " << _item << "\n";
    for (auto i : branches)
    {
        i->printTree(indent + 1);
    }
}
